package cn.bulibuqi.myblog.controller.backController;

import cn.bulibuqi.myblog.bean.User;
import cn.bulibuqi.myblog.service.UserService;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

/**
 * @author bulibuqi
 * @create 2021-12-17:05
 */
@Controller
@RequestMapping("/admin")
public class LoginController {
    @Autowired
    private UserService userService;

    @GetMapping
    public String login(){
        System.out.println("--------------------");
        return "admin/login";
    }

    @PostMapping("/login")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpSession session,
                        RedirectAttributes attributes){
        User user = userService.checkUser(username,password);
        if (user!=null){
            //用户名正确
            //不要把密码拿到前面去
            user.setPassword(null);
            session.setAttribute("user",user);
            return "admin/index";

        }else{
//            model.addAttribute("message","用户名和密码错误");
            attributes.addFlashAttribute("message","用户名和密码错误");
            //转发的话再次登录会有问题
            return "redirect:/admin";
        }
    }
}
